package com.sy.olddriver.service.impl;

import com.sy.olddriver.constant.AppConstant;
import com.sy.olddriver.dao.ProductDao;
import com.sy.olddriver.dao.impl.ProductDaoImpl;
import com.sy.olddriver.dto.CartInfo;
import com.sy.olddriver.dto.CartItem;
import com.sy.olddriver.entity.Product;
import com.sy.olddriver.entity.User;
import com.sy.olddriver.service.CartService;
import com.sy.olddriver.service.UserService;
import com.sy.olddriver.utils.CookieUtils;
import com.sy.olddriver.utils.RedisUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class CartServiceImpl implements CartService {
    private UserService userService = new UserServiceImpl();
    private ProductDao productDao = new ProductDaoImpl();

    @Override
    public void addCart(HttpServletRequest req, HttpServletResponse res) {
        String pid = req.getParameter("pid");
        String count = req.getParameter("count");
        String token = CookieUtils.getCookie(AppConstant.COOKIE_USER_TOKEN_NAME, req);
        User user = userService.getLoginUser(token);
        //如果用户没有登录
        if (user == null) {
            String tempCartCookie = CookieUtils.getCookie(AppConstant.COOKIE_TEMP_CART, req);
            //如果临时购物车cookie中的值为空
            if (StringUtils.isBlank(tempCartCookie)) {
                String tempCartCookieToken = UUID.randomUUID().toString().replace("-", "");
                CookieUtils.addCookie(AppConstant.COOKIE_TEMP_CART, tempCartCookieToken, res);
                RedisUtils.hincrBy(AppConstant.REDIS_TEMP_CART_KEY_PREFIX + tempCartCookieToken, pid, Long.parseLong(count));
            }
            //如果临时购车在cookie中的值不为空
            else {
                RedisUtils.hincrBy(AppConstant.REDIS_TEMP_CART_KEY_PREFIX + tempCartCookie, pid, Long.parseLong(count));
            }
        }
        //如果用户已经登录
        else {
            RedisUtils.hincrBy(AppConstant.REDIS_USER_CART_KEY_PREFIX + user.getId(), pid, Long.parseLong(count));
        }
    }

    @Override
    public void mergeCart(HttpServletRequest req, HttpServletResponse res, User user) {
        String tempCartCookie = CookieUtils.getCookie(AppConstant.COOKIE_TEMP_CART, req);
        if (StringUtils.isNotBlank(tempCartCookie)) {
            //获取redis中临时购物车的信息
            Map<String, String> tempCart = RedisUtils.hgetAll(AppConstant.REDIS_TEMP_CART_KEY_PREFIX + tempCartCookie);
            if (MapUtils.isNotEmpty(tempCart)) {
                for (Map.Entry<String, String> tempCartItem : tempCart.entrySet()) {
                    RedisUtils.hincrBy(AppConstant.REDIS_USER_CART_KEY_PREFIX + user.getId(), tempCartItem.getKey(), Long.parseLong(tempCartItem.getValue()));
                }

            }
        }
        CookieUtils.deleteCookie(AppConstant.COOKIE_TEMP_CART, req, res);
        RedisUtils.del(AppConstant.REDIS_TEMP_CART_KEY_PREFIX + tempCartCookie);
    }

    @Override
    public CartInfo getCartInfo(HttpServletRequest req, HttpServletResponse res) {
        String token = CookieUtils.getCookie(AppConstant.COOKIE_USER_TOKEN_NAME, req);
        User user = userService.getLoginUser(token);
        Map<String, String> cartMap = new HashMap<>();
        if (user == null) {
            cartMap = RedisUtils.hgetAll(AppConstant.REDIS_TEMP_CART_KEY_PREFIX + CookieUtils.getCookie(AppConstant.COOKIE_TEMP_CART, req));
        } else {
            cartMap = RedisUtils.hgetAll(AppConstant.REDIS_USER_CART_KEY_PREFIX + user.getId());
        }
        CartInfo cartInfo = new CartInfo();
        List<CartItem> cartItems = new ArrayList<>();
        BigDecimal totalPrice = new BigDecimal("0.0");
        for (Map.Entry<String, String> item : cartMap.entrySet()) {
            CartItem cartItem = new CartItem();
            Integer pid = Integer.parseInt(item.getKey());
            Product product = productDao.getProductById(pid);
            cartItem.setProduct(product);
            int count = Integer.parseInt(item.getValue());
            cartItem.setCount(count);
            BigDecimal unitPrice = new BigDecimal(String.valueOf(count)).multiply(new BigDecimal(String.valueOf(product.getPrice())));
            totalPrice = totalPrice.add(unitPrice);
            cartItem.setUnitPrice(unitPrice);
            cartItems.add(cartItem);
        }
        cartInfo.setCartItems(cartItems);
        cartInfo.setTotalPrice(totalPrice);
        return cartInfo;
    }

    @Override
    public void changeNum(HttpServletRequest req, HttpServletResponse res) {
        String pid = req.getParameter("pid");
        String count = req.getParameter("count");
        String token = CookieUtils.getCookie(AppConstant.COOKIE_USER_TOKEN_NAME, req);
        User user = userService.getLoginUser(token);
        if (user == null) {
            String cookieTempCart = CookieUtils.getCookie(AppConstant.COOKIE_TEMP_CART, req);
            if (StringUtils.isNotBlank(cookieTempCart)) {
                RedisUtils.hset(AppConstant.REDIS_TEMP_CART_KEY_PREFIX + cookieTempCart, pid, count);
            }
        } else {
            RedisUtils.hset(AppConstant.REDIS_USER_CART_KEY_PREFIX + user.getId(), pid, count);
        }

    }
}
